package net.cruciblesoftware.embers;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;


class ScreenSurface extends SurfaceView implements SurfaceHolder.Callback {

    public static int width, height;
    public static MotionEvent event;

    private LogicThread thread;
    private Scene scene;

    public ScreenSurface(Context context, AttributeSet attribs) {
        super(context, attribs);
        Log.i("SCREEN", "creating ScreenSurface...");
        this.getHolder().addCallback(this);
        scene = Scene.getInstance();
    }

    public LogicThread getThread() { return thread; }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        event = MotionEvent.obtain(ev);
        final int historySize = ev.getHistorySize();
        final int pointerCount = ev.getPointerCount();
        for(int h = 0; h < historySize; h++) {
            for(int p = 0; p < pointerCount; p++) {
                scene.addParticle(ev.getHistoricalX(p, h), 
                                  ev.getHistoricalY(p, h),
                                  ev.getHistoricalEventTime(h));
            }
        }
        for(int p = 0; p < pointerCount; p++) {
            scene.addParticle(ev.getX(p), ev.getY(p), ev.getEventTime());
        }
        return true;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.i("SCREEN", "surface is created...");
        width = this.getWidth();
        height = this.getHeight();
        thread = new LogicThread(this.getHolder());
        thread.setState(LogicThread.STATE_INTRO);
        thread.start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, 
                               int format, int w, int h) {
        width = w;
        height = h;
        Log.i("SCREEN", "surface changed: " + width + "x" + height);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.i("SCREEN", "surface holder is being destroyed...");
        thread.setState(LogicThread.STATE_CLOSING);

        // loop until thread terminates
        while(true) {
            try {
                thread.join();
                break;
            }
            catch(InterruptedException e) { }
        }
    }
}
